package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import io.swagger.v3.core.util.Json;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class TrackReceiver {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TrackInfoService trackInfoService;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE,durable="true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void updateTrackStat(String msg, Message message, Channel channel){
        if (!StringUtils.isEmpty(msg)){
            TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);
            String businessNo = trackStatMqVo.getBusinessNo();
            Boolean result = redisTemplate.opsForValue().setIfAbsent("trackStat:" + businessNo, businessNo, 10, TimeUnit.MINUTES);
            if (result){
                try {
                    trackInfoService.updateTrackStat(trackStatMqVo);
                } catch (Exception e) {
                    this.redisTemplate.delete("trackStat:"+businessNo);
//                    channel.basicNack(message.getMessageProperties().getvxDeliveryTag(),false,false);
                    throw new RuntimeException(e);
                }
            }

        }

        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
